from MasterMind import *
from socket import *
from random import choice

def make_pines():
    pines = []
    colors = ['blue','green','red','purple','orange','pink','lilac','brown','white','black']
    
    for color in colors:
        pines.append(Pine(color))
    return pines
    
def single(size):
    password = Block(size)
    pines_copy = pines[:-2]
    
    for position in xrange(size):
        pine = choice(pines_copy)
        pines_copy.pop(pines_copy.index(pine))
        password.add_pine(pine, position)
    return password
        

def server(porta):
   sock = socket()
   sock.bind(('',int(porta)))
   sock.listen(1)
   print 'Aguarde a conexao!...'
   client = sock.accept()
   print 'Conetado com %s' % client[1][0]
   nsock = client[0]
   return nsock

def conect(ip, porta):
   sock = socket()
   sock.connect((str(ip),int(porta)))
   return sock

def multiplayer(size):
    while True:
        opcao = input('1- Criar server,  2- Conectar: ')

        if opcao == 1:
            porta = input('Porta? ')
            sock = server(porta)
            break
   
        elif opcao == 2:
            ip = raw_input('IP: ')
            porta = input('Porta: ')
            sock = conect(ip, porta)
            break
    print 'Digite os pinos do password(ex: 0 2 1 3 4)'
    for i in xrange(len(pines[:-2])):
        print '%s - %s  ' % (i, pines[i])
    print
    passwordc = raw_input('Password? ')
    sock.send(passwordc)
    print 'Aguardando o outro jogador!'
    pines_pass = sock.recv(9).split()
    password = Block(size)
    for i in pines_pass:
        password.add_pine(pines[int(i)], pines_pass.index(i))
    sock.settimeout(0)
    return sock, password
    

def show_game(press_ok=True):
    print '='*50
    print 'Bloco |', block, '\n'
    
def finished():
    return block == password
 
block = Block(5)
password = Block(5)
pines = make_pines()
print 'PyMasterMind 0.1'
while True:
    opcao = input('1- Single Player   2- Multiplayer:')
    if opcao == 1:
        password = single(5)
        break
    elif opcao == 2:
        sock, password = multiplayer(5)
        break
    
press_ok = False
attempt = 0
function_list = ['Adcionar', 'Retirar', 'Ok']
while True:
    show_game(press_ok)
    
    if press_ok:
        if press_ok:
            print 'Dicas |', block.result_block(password), '\n'
            print 'Tentativa :', attempt, '\n'
            block = Block(5)
            press_ok = False
    
    try:
        print 'Adversario|',sock.recv(1024),'\n'
    except NameError:
        print '\n'
    except error:
        print '\n'
        
    if finished():
        print 'You Win'
        break
    elif attempt == 12:
        print 'Game Over'
        break
    
    for i in xrange(len(function_list)):
        print '%s - %s  ' % (i+1, function_list[i]),
    function = input('Opcao: ')
    
    if function == 1:
        for i in xrange(len(pines[:-2])):
            print '%s - %s  ' % (i, pines[i])
        print
        choice_pine = input('Pino? ')
        choice_position = input('Posicao?')
        if not block.add_pine(pines[choice_pine], choice_position-1):
            print 'Ja existe um pino!'
            
    elif function == 2:
        remove = input('Qual a posicao do pino? ')
        block.remove_pine(remove+1)
    elif function == 3:
        if not block.contains(None):
            press_ok = True
            attempt += 1
            try:
                sock.send(str(block))
            except NameError:
                pass
        else:
            print 'Bloco nao completado!'
    print
